ReactNative refを子コンポーネントに渡す
refはpropsで受け渡しすることはできない。
なので、React.forwardRefという方法でrefを子コンポーネントに渡す。そのやり方をここに記載しておく。
code: ok.js
import {createRef, forwardRef} from 'react';
const Parent = () => {
const ref = createRef();
return (
<Child ref={ref} />
)
}
const Child = forwardRef((props, ref) => {
return (
<TextInput ref={ref} />
)
})
ちなみに以下はできない
code: ng.js
import {createRef} from 'react';
const Parent = () => {
const ref = createRef();
return (
<Child />
)
}
const Child = (props) => {
return (
<TextInput ref={props.ref} />
)
}